﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.SqlClient;

namespace TinyForum.Test.Common
{
    public static class DBUtils
    {
        private static readonly NHibernate.Cfg.Configuration configuration = new NHibernate.Cfg.Configuration();
        private static bool configured = false;

        private static string ConnectionString
        {
            get { return configuration.Properties["connection.connection_string"]; }
        }

        private static void ConfigureNHibernate()
        {
            if (!configured)
            {
                configuration.Configure();
                configured = true;
            }
        }

        public static string GetMappedTableName<TClass>()
        {
            ConfigureNHibernate();
            return configuration.ClassMappings.Where(p => p.EntityName == typeof(TClass).FullName).First().Table.Name;
        }

        public static IEnumerable<string> AllTableNames
        {
            get
            {
                List<string> names = new List<string>();
                ConfigureNHibernate();
                configuration.ClassMappings.ToList().ForEach(p =>
                    names.Add(p.Table.Name));
                return names;
            }
        }

        public static void DeleteAllRecords(string tableName)
        {
            using (SqlConnection connection = new SqlConnection(ConnectionString))
            {
                connection.Open();
                using (SqlCommand command = new SqlCommand(string.Format("DELETE FROM [{0}]", tableName), connection))
                {
                    command.ExecuteNonQuery();
                }
                connection.Close();
            }
        }

        public static void DeleteAllRecords<TClass>()
        {
            string tableName = GetMappedTableName<TClass>();
            DeleteAllRecords(tableName);
        }

        public static void DeleteAllRecords()
        {
            foreach (var tableName in AllTableNames)
            {
                DeleteAllRecords(tableName);
            }
        }
    }
}
